#pragma once
#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string>



namespace wyl
{
    class Sock
    {
    public:
        //创建
        static int Socket()
        {
            int sock = socket(AF_INET,SOCK_STREAM,0);
            if(sock < 0)
            {
                std::cout<<"socket failed"<<std::endl;
                exit(1);
            }
            return sock;
        }
        //绑定
        static void Bind(int sock,uint16_t port)
        {
            struct sockaddr_in local;
            local.sin_port = htons(port);
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY; 
            if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0 )
            {
                std::cout<<"Bind failed"<<std::endl;
                exit(2);
            }
            else
            {
                std::cout<<"Bind Succeed"<<std::endl;
            }
        }
        //监听
        static void Listen(int listen_sock)
        {
            if(listen(listen_sock,5) < 0)
            {
                std::cout<<"Listen failed"<<std::endl;
                exit(3);
            }
            else
                std::cout<<"Listen succeed"<<std::endl;
        }
        //接收
        static int Accpet(int sock)
        {
            struct sockaddr_in client;
            socklen_t len;
            int fd = accept(sock,(struct sockaddr*)&client,&len);
            if( fd < 0)
            {
                std::cout<<"Accept failed"<<std::endl;
                exit(4);
            }     
            return fd;
        }

        //连接
        static void Connect(int sock,uint16_t port,std::string ser_ip)
        {
            struct sockaddr_in server;
            server.sin_port = htons(port);
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(ser_ip.c_str());
            if(connect(sock,(struct sockaddr*)&server,sizeof(server))  < 0 )
            {
                std::cout<<"Connect failed"<<std::endl;
                exit(5);
            }
            else
                std::cout<<"Connect succeed"<<std::endl;
        }


    };
}